#include "dialogi2c.h"

#include "QDebug"
#include "ui_dialogi2c.h"

DialogI2C::DialogI2C(QWidget *parent) : QDialog(parent), ui(new Ui::DialogI2C)
{
    QStringList gpio = {"B_HAL_GPIOA", "B_HAL_GPIOB", "B_HAL_GPIOC", "B_HAL_GPIOD",
                        "B_HAL_GPIOE", "B_HAL_GPIOF", "B_HAL_GPIOG"};
    QStringList pin  = {"B_HAL_PIN0",  "B_HAL_PIN1",  "B_HAL_PIN2",  "B_HAL_PIN3",
                       "B_HAL_PIN4",  "B_HAL_PIN5",  "B_HAL_PIN6",  "B_HAL_PIN7",
                       "B_HAL_PIN8",  "B_HAL_PIN9",  "B_HAL_PIN10", "B_HAL_PIN11",
                       "B_HAL_PIN12", "B_HAL_PIN13", "B_HAL_PIN14", "B_HAL_PIN15"};

    ui->setupUi(this);
    ui->i2c_checkbox_sim->setChecked(false);
    ui->combox_clk_pin->setEnabled(false);
    ui->combox_sda_pin->setEnabled(false);
    ui->combox_clk_port->setEnabled(false);
    ui->combox_sda_port->setEnabled(false);
    ui->combox_i2c->setEnabled(true);
    ui->line_edit_addr->setText("0x00");

    ui->combox_i2c->addItems({"B_HAL_I2C_1", "B_HAL_I2C_2", "B_HAL_I2C_3", "B_HAL_I2C_4"});

    ui->combox_clk_port->addItems(gpio);
    ui->combox_sda_port->addItems(gpio);

    ui->combox_clk_pin->addItems(pin);
    ui->combox_sda_pin->addItems(pin);

    i2c_cfg_str.clear();

    this->setModal(true);
}

DialogI2C::~DialogI2C()
{
    delete ui;
}

void DialogI2C::on_i2c_checkbox_sim_stateChanged(int arg1)
{
    if (ui->i2c_checkbox_sim->isChecked())
    {
        ui->combox_clk_pin->setEnabled(true);
        ui->combox_sda_pin->setEnabled(true);
        ui->combox_clk_port->setEnabled(true);
        ui->combox_sda_port->setEnabled(true);
        ui->combox_i2c->setEnabled(false);
    }
    else
    {
        ui->combox_clk_pin->setEnabled(false);
        ui->combox_sda_pin->setEnabled(false);
        ui->combox_clk_port->setEnabled(false);
        ui->combox_sda_port->setEnabled(false);
        ui->combox_i2c->setEnabled(true);
    }
}

void DialogI2C::on_buttonbox_i2c_accepted()
{
    QString dev_addr      = ".dev_addr = " + ui->line_edit_addr->text() + ", ";
    QString is_simulation = ".is_simulation = ";
    QString _if           = "";
    if (ui->i2c_checkbox_sim->isChecked())
    {
        is_simulation.append("1, ");
        _if.append("._if.simulating_i2c.clk = {" + ui->combox_clk_port->currentText() + ", " +
                   ui->combox_clk_pin->currentText() + "}, ");
        _if.append("._if.simulating_i2c.sda = {" + ui->combox_sda_port->currentText() + ", " +
                   ui->combox_sda_pin->currentText() + "}, ");
    }
    else
    {
        is_simulation.append("0, ");
        _if.append("._if.i2c = " + ui->combox_i2c->currentText() + ", ");
    }

    i2c_cfg_str = "{" + dev_addr + " " + is_simulation + " " + _if + "}";
    emit send_string(i2c_cfg_str);
}
